import Vue from 'vue';
import Vuex from 'vuex';
import { getOneById } from '../api/elasticApi';
import { getCookie, setCookie } from '../common/cookie';
Vue.use(Vuex);

const SET_CURRENT_COOK = 'SET_CURRENT_COOK';
const SET_HAS_BROWSER_JOINED = 'SET_HAS_BROWSER_JOINED';
const SET_HAS_HOME_JOINED = 'SET_HAS_HOME_JOINED';

export default new Vuex.Store({
  state: {
    currentCook: null,
    hasHomeJoined: getCookie('hasHomeJoined'),
    hasBrowserJoined: getCookie('hasBrowserJoined')
  },
  mutations: {
    [SET_CURRENT_COOK](state, payload) {
      state.currentCook = payload;
    },
    [SET_HAS_BROWSER_JOINED](state, payload) {
      state.hasBrowserJoined = payload;
    },
    [SET_HAS_HOME_JOINED](state, payload) {
      state.hasHomeJoined = payload;
    }
  },
  getters: {
    getCurrentCook: state => state.currentCook,
    hasHomeJoined: state => state.hasHomeJoined,
    hasBrowserJoined: state => state.hasBrowserJoined
  },
  actions: {
    setCurrentCook(store, id) {
      getOneById(id)
        .then(res => {
          store.commit('SET_CURRENT_COOK', res.data['_source']);
        })
        .catch(err => {
          console.log(err);
        });
    },
    setHasHomeJoined(store) {
      setCookie('hasHomeJoined', true, 1);
      store.commit('SET_HAS_HOME_JOINED', true);
    },
    setHasBrowserJoined(store) {
      setCookie('hasBrowserJoined', true, 1);
      store.commit('SET_HAS_BROWSER_JOINED', true);
    }
  }
});
